<template>
  <view class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部导航 -->
    <PageHeader title="签到详情" :showBack="true" />

    <!-- 人员基本信息 -->
    <view class="bg-white p-[32rpx] mb-[20rpx]">
      <view class="flex items-center mb-[24rpx]">
        <view class="w-[120rpx] h-[120rpx] rounded-full bg-[#e3f2fd] flex items-center justify-center mr-[24rpx] overflow-hidden">
          <img
            v-if="personDetail.avatar"
            :src="personDetail.avatar"
            class="w-full h-full object-cover"
            alt="头像"
          />
          <text v-else class="text-[48rpx] font-bold text-[#2196F3]">
            {{ personDetail.name?.charAt(0) || '用' }}
          </text>
        </view>
        <view class="flex-1">
          <view class="text-[36rpx] font-bold text-[#222] mb-[12rpx]">
            {{ personDetail.name }}
          </view>
          <view class="text-[28rpx] text-[#666] mb-[8rpx]">
            {{ personDetail.phone }}
          </view>
          <view
            class="px-[16rpx] py-[8rpx] rounded-[12rpx] text-[24rpx] font-medium inline-block"
            :class="
              personDetail.signed
                ? 'bg-[#e8f5e9] text-[#2e7d32]'
                : 'bg-[#fff3e0] text-[#f57c00]'
            "
          >
            {{ personDetail.signed ? '已签到' : '未签到' }}
          </view>
        </view>
      </view>

      <!-- 统计信息 -->
      <view class="grid grid-cols-3 gap-[20rpx]">
        <view class="text-center">
          <view class="text-[32rpx] font-bold text-[#2196F3]">{{ personDetail.totalSignCount }}</view>
          <view class="text-[24rpx] text-[#666]">总签到次数</view>
        </view>
        <view class="text-center">
          <view class="text-[32rpx] font-bold text-[#4caf50]">{{ personDetail.continuousSignCount }}</view>
          <view class="text-[24rpx] text-[#666]">连续签到</view>
        </view>
        <view class="text-center">
          <view class="text-[32rpx] font-bold text-[#ff9800]">{{ personDetail.signRate }}%</view>
          <view class="text-[24rpx] text-[#666]">签到率</view>
        </view>
      </view>
    </view>

    <!-- 最近签到记录 -->
    <view class="bg-white p-[32rpx] mb-[20rpx]">
      <view class="text-[32rpx] font-bold text-[#222] mb-[24rpx]">最近签到记录</view>
      
      <view v-if="signRecords.length > 0">
        <view
          v-for="(record, index) in signRecords"
          :key="record.id"
          class="border-l-[4rpx] border-l-[#2196F3] bg-[#f8f9fa] rounded-[12rpx] p-[24rpx] mb-[16rpx]"
        >
          <view class="flex justify-between items-start mb-[12rpx]">
            <view class="text-[28rpx] font-bold text-[#222]">
              第{{ record.signCount }}次签到
            </view>
            <view class="text-[24rpx] text-[#666]">
              {{ record.signTime }}
            </view>
          </view>
          
          <view class="text-[26rpx] text-[#666] mb-[8rpx]">
            签到地点：{{ record.signLocation }}
          </view>
          
          <view class="text-[24rpx] text-[#999]">
            签到方式：{{ record.signMethod }}
          </view>
        </view>
      </view>
      
      <view v-else class="text-center py-[60rpx]">
        <IconFont name="empty" class="text-[80rpx] text-[#ccc] mb-[16rpx]" />
        <view class="text-[26rpx] text-[#999]">暂无签到记录</view>
      </view>
    </view>

    <!-- 签到统计图表 -->
    <view class="bg-white p-[32rpx] mb-[20rpx]">
      <view class="text-[32rpx] font-bold text-[#222] mb-[24rpx]">签到统计</view>
      
      <!-- 月度签到统计 -->
      <view class="mb-[32rpx]">
        <view class="text-[28rpx] font-medium text-[#222] mb-[16rpx]">本月签到情况</view>
        <view class="flex justify-between items-end h-[160rpx]">
          <view
            v-for="(day, index) in monthlySignData"
            :key="index"
            class="flex flex-col items-center"
          >
            <view class="text-[20rpx] mb-[8rpx] text-[#666]">{{ day.date }}</view>
            <view 
              class="w-[24rpx] rounded-t-[4rpx] transition-all duration-300"
              :class="day.signed ? 'bg-[#4caf50]' : 'bg-[#e0e0e0]'"
              :style="{ height: `${day.signed ? 120 : 20}rpx` }"
            ></view>
            <view class="text-[20rpx] mt-[8rpx] text-[#666]">
              {{ day.signed ? '✓' : '○' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 签到时间分布 -->
      <view>
        <view class="text-[28rpx] font-medium text-[#222] mb-[16rpx]">签到时间分布</view>
        <view class="grid grid-cols-4 gap-[16rpx]">
          <view
            v-for="(timeSlot, index) in timeDistribution"
            :key="index"
            class="text-center"
          >
            <view class="text-[24rpx] font-bold text-[#2196F3]">{{ timeSlot.count }}</view>
            <view class="text-[22rpx] text-[#666]">{{ timeSlot.label }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 备注信息 -->
    <view v-if="personDetail.remark" class="bg-white p-[32rpx] mb-[20rpx]">
      <view class="text-[32rpx] font-bold text-[#222] mb-[16rpx]">备注信息</view>
      <view class="bg-[#fff3e0] rounded-[12rpx] p-[20rpx]">
        <view class="text-[26rpx] text-[#666]">{{ personDetail.remark }}</view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="bg-white p-[32rpx] mb-[20rpx]">
      <view class="flex gap-[20rpx]">
        <nut-button
          type="primary"
          class="flex-1 bg-[#4caf50] border-none"
          @click="handleExportRecord"
        >
          导出记录
        </nut-button>
        <nut-button
          type="info"
          class="flex-1 bg-[#e3f2fd] text-[#2196F3] border-none"
          @click="handleSendMessage"
        >
          发送消息
        </nut-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import PageHeader from '@/components/PageHeader.vue'
import { post } from '@/utils/request'

// 定义接口
interface SignRecord {
  id: number
  signTime: string
  signLocation: string
  signMethod: string
  signCount: number
}

interface PersonDetail {
  id: number
  name: string
  phone: string
  avatar?: string
  signed: boolean
  totalSignCount: number
  continuousSignCount: number
  signRate: number
  remark?: string
}

interface MonthlySignDay {
  date: string
  signed: boolean
}

interface TimeSlot {
  label: string
  count: number
}

// 路由参数
const personId = ref<number>(0)
const taskId = ref<number>(0)

// 数据
const personDetail = ref<PersonDetail>({
  id: 0,
  name: '',
  phone: '',
  signed: false,
  totalSignCount: 0,
  continuousSignCount: 0,
  signRate: 0
})

const signRecords = ref<SignRecord[]>([])
const monthlySignData = ref<MonthlySignDay[]>([])
const timeDistribution = ref<TimeSlot[]>([
  { label: '早上', count: 0 },
  { label: '中午', count: 0 },
  { label: '下午', count: 0 },
  { label: '晚上', count: 0 }
])

// 获取人员详情
const getPersonDetail = async () => {
  try {
    const res = await post('/task/person-detail', {
      personId: personId.value,
      taskId: taskId.value
    })
    
    if (res.code === 0) {
      personDetail.value = {
        id: res.data.id,
        name: res.data.name || '未知用户',
        phone: res.data.phone || '未知手机号',
        avatar: res.data.avatar,
        signed: res.data.signed || false,
        totalSignCount: res.data.totalSignCount || 0,
        continuousSignCount: res.data.continuousSignCount || 0,
        signRate: res.data.signRate || 0,
        remark: res.data.remark
      }
    } else {
      Taro.showToast({
        title: res.message || '获取详情失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取人员详情失败:', error)
    Taro.showToast({
      title: '获取详情失败',
      icon: 'none'
    })
  }
}

// 获取签到记录
const getSignRecords = async () => {
  try {
    const res = await post('/task/sign-records', {
      personId: personId.value,
      taskId: taskId.value
    })
    
    if (res.code === 0) {
      signRecords.value = res.data.map((item: any) => ({
        id: item.id,
        signTime: item.signTime,
        signLocation: item.signLocation,
        signMethod: item.signMethod || '自动签到',
        signCount: item.signCount
      }))
    }
  } catch (error) {
    console.error('获取签到记录失败:', error)
  }
}

// 获取月度签到数据
const getMonthlySignData = async () => {
  try {
    const res = await post('/task/monthly-sign-data', {
      personId: personId.value,
      taskId: taskId.value
    })
    
    if (res.code === 0) {
      monthlySignData.value = res.data
    }
  } catch (error) {
    console.error('获取月度签到数据失败:', error)
  }
}

// 获取时间分布数据
const getTimeDistribution = async () => {
  try {
    const res = await post('/task/time-distribution', {
      personId: personId.value,
      taskId: taskId.value
    })
    
    if (res.code === 0) {
      timeDistribution.value = res.data
    }
  } catch (error) {
    console.error('获取时间分布数据失败:', error)
  }
}

// 导出记录
const handleExportRecord = () => {
  Taro.showModal({
    title: '导出记录',
    content: '确定要导出该人员的签到记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const exportRes = await post('/task/export-person-record', {
            personId: personId.value,
            taskId: taskId.value
          })
          
          if (exportRes.code === 0) {
            Taro.showToast({
              title: '导出成功',
              icon: 'success'
            })
          } else {
            Taro.showToast({
              title: exportRes.message || '导出失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('导出记录失败:', error)
          Taro.showToast({
            title: '导出失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 发送消息
const handleSendMessage = () => {
  Taro.navigateTo({
    url: `/pages/message/chat?userId=${personId.value}&taskId=${taskId.value}`
  })
}

// 页面加载
onMounted(() => {
  const params = Taro.getCurrentInstance().router?.params
  if (params?.id && params?.taskId) {
    personId.value = Number(params.id)
    taskId.value = Number(params.taskId)
    
    // 获取数据
    getPersonDetail()
    getSignRecords()
    getMonthlySignData()
    getTimeDistribution()
  } else {
    Taro.showToast({
      title: '缺少必要参数',
      icon: 'none'
    })
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500)
  }
})
</script>

<style lang="scss" scoped>
.nut-button {
  border-radius: 12rpx !important;
  font-weight: 500 !important;
}

// 添加悬停效果
.bg-white {
  transition: all 0.3s ease;
}
</style>
